﻿import urllib2
import json
import uuid
import hashlib
import base64
import re
import datetime
from django.utils import timezone
from clients.models import Operation, Agreement, Client
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Max, F

_LOGIN_ = 'auto@gtlink.ru'
_PASSWORD_ = 'fhcty2805'
_API_URL_ = 'https://paymaster.ru/partners/rest/listPaymentsFilter'
_STATE_ = 'COMPLETE'
_DESC_ = u'Оплата с сайта'


def json_date_as_datetime(jd):
    sign = jd[-7]
    if sign not in '-+' or len(jd) == 13:
        millisecs = int(jd[6:-2])
    else:
        millisecs = int(jd[6:-7])
        hh = int(jd[-7:-4])
        mm = int(jd[-4:-2])
        if sign == '-': mm = -mm
        millisecs += (hh * 60 + mm) * 60000
    return datetime.datetime(1970, 1, 1) \
           + datetime.timedelta(microseconds=millisecs * 1000)


class Command(BaseCommand):
    args = ''
    help = 'Gets payments from payment system that came since the last time the command was executed'

    def handle(self, *args, **options):
        while(self.getPayments()):
            pass

    def getPayments(self):
        _NONCE_ = str(uuid.uuid4())
        last_op = Operation.objects.annotate(max_date=Max('date')).filter(date=F('max_date'))
        _PERIOD_FROM_ = ""
        if last_op:
            _PERIOD_FROM_ = last_op[0].date.strftime("%y-%m-%d")
        # login;password;nonce;accountID;siteAlias;periodFrom;periodTo;invoiceID;state
        hash_str = '%s;%s;%s;%s;%s;%s;%s;%s;%s' % (_LOGIN_, _PASSWORD_, _NONCE_, '', '', _PERIOD_FROM_, '', '', _STATE_)
        hash_sha1 = hashlib.sha1(hash_str).digest()
        hash_b64 = base64.b64encode(hash_sha1)
        params = ""
        if _PERIOD_FROM_:
            params = 'login=%s&periodFrom=%s&nonce=%s&state=%s&hash=%s' % (
            _LOGIN_, _PERIOD_FROM_, _NONCE_, _STATE_, hash_b64)
        else:
            params = 'login=%s&nonce=%s&state=%s&hash=%s' % (_LOGIN_, _NONCE_, _STATE_, hash_b64)
        url = '%s?%s' % (_API_URL_, params)

        r = urllib2.urlopen(url)

        response = json.load(r)
        overflow = response['Response']['Overflow']
        for i in response['Response']['Payments']:
            self.createOperation(i)
        return overflow

    def createOperation(self, op):
        if len(Operation.objects.filter(payment_id=op['PaymentID'])) > 0:
            return
        num_re = re.match('[^\d]+(\d+)$', unicode(op['Purpose']))
        if not num_re:
            return
        num = num_re.group(1)
        agreement = Agreement.objects.filter(number=num).first()
        date = json_date_as_datetime(op['LastUpdate'])
        obj = Operation(name=unicode(op['Purpose']), amount=op['Amount'], date=date, payment_id=op['PaymentID'],
                        agreement_number=num)
        obj.author_id = 1
        if agreement:
            obj.agreement = agreement
            obj.client = agreement.client

        obj.save()

